import React from 'react'
import { useRef, useEffect, useState } from 'react'
import * as echarts from 'echarts';
import { getMap } from '../../api/index'
import './map.scss'
import 'echarts-gl'


function map() {
  let Map = useRef(null)
  console.log(getMap);

  let newArr = [{ name: '中国', adcode: 10000 }];
  let fun = (adcode: any, name: any) => {
    var myChart = echarts.init(Map.current);
    getMap(adcode).then(res => {
      console.log('地图',res );
      echarts.registerMap(name, res.data)
      let option = {
        visualMap: {
          min: 1,
          max: 80,
          text: ['High', 'Low'],
          realtime: false,
          calculable: true,
          inRange: {
            color: ['lightskyblue', 'yellow', 'orangered']
          }
        },
        series: [
          {
            name: name,
            type: 'map3D',
            // type:'map',
            map: name,
            label: {
              show: true
            },
            data: res.data.features.map((item: any) => {
              return {
                name: item.properties.name,
                value: item.properties.childrenNum,
                adcode: item.properties.adcode,
              }
            })
          }
        ]
      }
      myChart.setOption(option)
      // myChart.off('click', onclick);
      // myChart.off('contextmenu', oncontextmenu)
      //点击下钻
      const goclick = (e:any) => {

        myChart.off('click', goclick)
        myChart.off('mousedown', goback)
        //  myChart.off('contextmenu', goback) 

        newArr.push({
          name: e.data.name,
          adcode: e.data.adcode
        })
        fun(e.data.adcode, e.data.name)
      }
      //返回
      // 3D版
      const goback=(e:any)=>{
          if(e.event?.event?.button !=2) return false
          newArr.pop()
          if(newArr.length<1){
            return false
          }
          fun(
            newArr[newArr.length-1].name,
            newArr[newArr.length-1].adcode,
          )
      }
      // const goback = (e:any) => {
      //    e.event.stop() 
      //   newArr.pop()
      //   let { adcode, name } = newArr[newArr.length - 1]
      //   console.log(adcode, name);
      //   fun(adcode, name);
      // }

      myChart.on('click', goclick)
      console.log(newArr);
      // myChart.on('contextmenu', goback)
      myChart.on('mousedown', goback)
    })
    
   
  }
  useEffect(() => {
    fun(100000, '中国')
  }, [])

  return (
    <div className='MapBox' ref={Map} onContextMenu={(e)=>e.preventDefault()}>map</div>
  )
}

export default map
